/**
 * Created by jiadx on 2016/3/18.
 */
'use strict';

angular.module('Report')
    .controller('WorkOutputController', ['$scope', '$http', '$q', '$stateParams', '$timeout', 'BaseModule', 'BaseEnum', 'BaseFunction',
        function($scope, $http, $q, $stateParams, $timeout, BaseModule, BaseEnum, BaseFunction) {
            BaseModule.initModule($scope, 'WorkOutput');
            $scope.selectDateType = 0;
            $scope.startDateTime = null;
            $scope.endDateTime = null;
            $scope.dateIsEnable = false;
            $scope.dateType = {
                today: { Value: 0, Text: '今天' },
                yesterday: { Value: 1, Text: '昨天' },
                thisWeek: { Value: 2, Text: '本周' },
                thisMonth: { Value: 3, Text: '本月' },
                diyDate: { Value: 4, Text: '自定义' }
            };

            var todayStart = new Date(new Date(new Date().setDate(new Date().getDate())).setHours(0, 0, 0, 0));
            var yesterdayStart = new Date(new Date(new Date().setDate(new Date().getDate() - 1)).setHours(0, 0, 0, 0));
            var todayEnd = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);

            $scope.selectType = function() {
                if ($scope.selectDateType === 4) {
                    $scope.dateIsEnable = 'true';
                }else{
                    $scope.dateIsEnable = 'false';
                }
            };

            $scope.btnQuery = function() {
                var condition;
                if ($scope.selectDateType === 0) {
                    condition = { BizDate: { $gt: todayStart, $lt: todayEnd } };
                } else if ($scope.selectDateType === 1) {
                    condition = { BizDate: { $gt: yesterdayStart, $lt: todayStart } };
                } else if ($scope.selectDateType === 2) {
                    var weekDay = getCurrentWeek();
                    condition = { BizDate: { $gt: weekDay.monday, $lt: weekDay.sunday } };
                } else if ($scope.selectDateType === 3) {
                    var monthDay = getCurrentMonth();
                    condition = { BizDate: { $gt: monthDay.firstDay, $lt: monthDay.lastDay } };
                } else if ($scope.selectDateType === 4) {
                    condition = { BizDate: { $gt: $scope.startDateTime, $lt: $scope.endDateTime } };
                }
                if ($scope.selectDep) {
                    condition.Department = $scope.selectDep._id;
                }
                $scope.init(condition);
            };

            function refresh(workArray, output, avg) {
                var myChart = echarts.init(document.getElementById('main'));
                var option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['工序产量', '平均产量']
                    },
                    xAxis: [{
                        type: 'category',
                        data: workArray
                    }],
                    yAxis: [{
                        type: 'value',
                        name: '产量',
                        min: 0,
                        // max: 500,
                        interval: 50,
                        axisLabel: {
                            formatter: '{value} pcs'
                        }
                    }],
                    series: [{
                        name: '工序产量',
                        type: 'bar',
                        data: output
                    }, {
                        name: '平均产量',
                        type: 'line',
                        data: avg
                    }]
                };
                myChart.setOption(option);
                window.onresize = myChart.resize;
            }

            $scope.init = function(condition) {
                if (!condition) {
                    condition = {};
                }
                $scope.Module.WorkOutput.find(condition, null, [{
                    path: 'Department',
                    select: 'Code Name'
                }, {
                    path: 'User',
                    select: 'Code Name'
                }, {
                    path: 'Work',
                    select: 'Code Name'
                }, {
                    path: 'ItemMaster',
                    select: 'Code Name'
                }], function(records) {
                    var workObj = {},
                        workArray = [],
                        output = [],
                        avg = [],
                        workCount = 0,
                        total = 0;
                    angular.forEach(records, function(record) {
                        if (workObj.hasOwnProperty(record.Work.Code)) {
                            workObj[record.Work.Code].CompleteQty += record.CompleteQty;
                        } else {
                            workCount++;
                            workObj[record.Work.Code] = {};
                            workObj[record.Work.Code].CompleteQty = record.CompleteQty;
                            workObj[record.Work.Code].Name = record.Work.Name;
                        }
                        total += record.CompleteQty;
                    });
                    angular.forEach(workObj, function(value) {
                        workArray.push(value.Name);
                        output.push(value.CompleteQty);
                        avg.push(total / workCount);
                    });
                    refresh(workArray, output, avg);
                });
            };

            // $scope.init();

            function getCurrentWeek() {
                //获取当前时间
                var currentDate = new Date();
                //返回date是一周中的某一天
                var week = currentDate.getDay();
                //返回date是一个月中的某一天
                var month = currentDate.getDate();
                //一天的毫秒数
                var millisecond = 1000 * 60 * 60 * 24;
                //减去的天数
                var minusDay = week != 0 ? week - 1 : 6;
                //alert(minusDay);
                //本周 周一
                var monday = new Date(new Date(new Date().toLocaleDateString()).getTime() - (minusDay * millisecond));
                //本周 周日
                var sunday = new Date(monday.getTime() + (6 * millisecond) + 24 * 60 * 60 * 1000 - 1);

                //返回
                return {
                    monday: monday,
                    sunday: sunday
                };
            }

            function getCurrentMonth() {
                //获取当前时间
                var currentDate = new Date();
                //获得当前月份0-11
                var currentMonth = currentDate.getMonth();
                //获得当前年份4位年
                var currentYear = currentDate.getFullYear();
                //求出本月第一天
                var firstDay = new Date(currentYear, currentMonth, 1);

                //当为12月的时候年份需要加1
                //月份需要更新为0 也就是下一年的第一个月
                if (currentMonth == 11) {
                    currentYear++;
                    currentMonth = 0; //就为
                } else {
                    //否则只是月份增加,以便求的下一月的第一天
                    currentMonth++;
                }

                //一天的毫秒数
                var millisecond = 1000 * 60 * 60 * 24;
                //下月的第一天
                var nextMonthDayOne = new Date(currentYear, currentMonth, 1);
                //求出上月的最后一天
                var lastDay = new Date(nextMonthDayOne.getTime() - millisecond + +24 * 60 * 60 * 1000 - 1);

                //返回
                return {
                    firstDay: firstDay,
                    lastDay: lastDay
                };
            }
        }
    ])
